-1
我正在学习android和webservices
。我有一个使用okHttp
发送数据的android应用程序,我需要在我的服务器上获取这些数据并将其放入数据库。我有一点经验调用并从webservices
获取数据,但从未收到数据。ASP.NET如何使用OkHttp从Android应用程序接收HTTP数据
据我所知,在ASP.Net中我需要使用HttpHandler
,我已经看到了一些例子,但他们似乎总是按照请求返回数据。您如何保持HttpHandler
始终监听此特定传入数据?
这里是我的示例android应用程序的代码。
public class MainActivity extends Activity {
TextView outputText;
Button sendData;
EditText edtUser, edtPass;
final String URL = "http://serviceapi.skholingua.com/open-feeds/display_received_params.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputText = (TextView) findViewById(R.id.textView1);
outputText.setMovementMethod(new ScrollingMovementMethod());
sendData = (Button) findViewById(R.id.button1);
edtUser = (EditText) findViewById(R.id.editText1);
edtPass = (EditText) findViewById(R.id.editText2);
sendData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String userName = edtUser.getText().toString();
String passWord = edtPass.getText().toString();
OkHttpHandler handler = new OkHttpHandler(userName, passWord);
String result = null;
try {
result = handler.execute(URL).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputText.append(result + "\n");
}
});
}
的Class
public class OkHttpHandler extends AsyncTask<String, Void, String> {
OkHttpClient client = new OkHttpClient();
String userName, passWord;
public OkHttpHandler(String userName, String passWord) {
// TODO Auto-generated constructor stub
this.userName = userName;
this.passWord = passWord;
}
@Override
protected String doInBackground(String... params) {
RequestBody formBody = new FormEncodingBuilder()
.add("name", userName)
.add("pass", passWord)
.build();
Request request = new Request.Builder()
.url(params[0]).post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response.toString());
return response.body().string();
} catch (Exception e) {
}
return null;
}
的URL
将改为无论我在我的服务器上创建。我的问题是......这将发送什么类型的数据?我需要在我的服务器上创建什么来摄取它? 如果有人有一个很有帮助的例子。
嘿..谢谢帮助...我现在正在研究Web API,但仍然困惑......请你详细说明你的示例是什么?查找Web API我发现了大量关于如何从Web服务获取数据的示例,但没有太多关于如何监听数据发布到您的服务的示例。 – meyvn
已更新的示例 – Mattias