用户必须将标题和数字输入两个EditText。一旦他点击提交,他在EditText中写的内容将被转换为String。 现在面临的问题是,如何将这些字符串发布到RESTful Web服务
这是我的代码
submit.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String tit = null;
String number = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:3000/api");
if(title.getText()!=null){
tit = title.getText().toString();
}
if(num.getText()!=null){
number = num.getText().toString();
}
}
});
请任何人都可以指导我或指导我如何做。
答案 0 :(得分:1)
submit.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String tit = null;
String number = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:3000/api");
if(title.getText()!=null){
tit = title.getText().toString();
}
if(num.getText()!=null){
number = num.getText().toString();
}
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("title", tit));
nameValuePairs.add(new BasicNameValuePair("number", number));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpPost);
}
});
答案 1 :(得分:0)
@Assad永远不会在UI线程上制作网络内容。
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tit = title.getText().toString();
String number = num.getText().toString();
new PostDataTask().execute(new String[] { tit, number });
}
});
在AsyncTask或其他工作线程
下发出Http请求class PostDataTask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:3000/api");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("title", params[0]));
nameValuePairs.add(new BasicNameValuePair("number", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// HttpResponse response = httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpClient.execute(httpPost, responseHandler);
return true;
} catch (HttpResponseException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
// success
} else {
// failure
}
}
}