如何在Android中创建一个httppost请求?
问题描述:
我知道这应该是很容易在网上找到,但没有文章解决了我的问题,所以我来这么一段help.I想使android系统的httppost请求一个WCF RESTful Web服务。我想创建一个xml然后我想将其发布到该服务并获得该服务的响应。如何在Android中创建一个httppost请求?
我创建了一个WCF REST服务,它有接受XML和应对back.Here是该方法的代码的方法:
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "DoWork1/{xml}",
BodyStyle = WebMessageBodyStyle.Wrapped)]
XElement DoWork1(string xml);
public XElement DoWork1(string xml)
{
StreamReader reader = null;
XDocument xDocRequest = null;
string strXmlRequest = string.Empty;
reader = new StreamReader(xml);
strXmlRequest = reader.ReadToEnd();
xDocRequest = XDocument.Parse(strXmlRequest);
string response = "<Result>OK</Result>";
return XElement.Parse(response);
}
下面是Android的代码发布XML:
String myXML = "<? xml version=1.0> <Request> <Elemtnt> <data id=\"1\">E1203</data> <data id=\"2\">E1204</data> </Element> </Request>";
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("http://192.168.0.15/Httppost/Service1.svc/DoWork1/"+myXML);
此代码会在路径异常中抛出非法字符。
我怎样才能使发布的XML文件从Android这项服务。任何建议将非常感激。
答
public class HTTPPostActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
makePostRequest();
}
private void makePostRequest() {
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("www.example.com");
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", "test_user"));
nameValuePair.add(new BasicNameValuePair("password", "123456789"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
}
}
答
要连接到Android上的WCF服务,您必须使用外部库如ksoap。 enter link description here
然后你就可以适应您的需求这个类:只有在应用context.Pass数据到活动
SoapWorker.SoapRequest request = new SoapWorker.SoapRequest(URL,METHOD_NAME,NAMESPACE);
request.addParam(KEY,VALUE);
....
request.addParam(KEY,VALUE);
SoapWorker worker = new SoapWorker(){
@Override
public Object parseResponse(Object response) {
if(response==null)
return null;
//parse response
// this is background thread
return response;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// this is ui thread
//update your ui
}
};
worker.execute(request);
使用此asynck任务:
public abstract class SoapWorker extends AsyncTask<SoapWorker.SoapRequest,Void,Object> {
public static class SoapRequest{
private LinkedHashMap<String,Object> params;
private String methodName;
private String namespace;
private String actionName;
private String url;
public SoapRequest(String url, String methodName,String namespace){
this.methodName = methodName;
this.params = new LinkedHashMap<>();
this.namespace=namespace;
this.actionName=this.namespace + "IService/" + methodName;
this.url=url;
}
public void addParam(String key,Object value){
this.params.put(key,value);
}
}
@Override
protected Object doInBackground(SoapRequest input) {
try {
SoapObject request = new SoapObject(input.namespace, input.methodName);
for(Map.Entry<String, Object> entry : input.params.entrySet()){
request.addProperty(entry.getKey(),entry.getValue());
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(input.url);
androidHttpTransport.call(input.actionName, envelope);
input.params.clear();
return parseResponse(envelope.getResponse());
} catch (Exception e) {
Log.e("SoapWorker", "error " + e);
return e;
}
}
@WorkerThread
public abstract Object parseResponse(Object response);
}
使用这个类像/片段仅使用来自绿色roboot或otto的EventBus。
我想知道downvoting的原因?? –
你为什么用附加URL myXML,你应该设置XML作为POST请求体 – QAMAR
,因为当我试图通过它像其他方式httppost.setentity方法..它总是告诉我找不到 –