gpt4 book ai didi

java - 如何从 Android 将参数发布到 Web 服务?

转载 作者:行者123 更新时间:2023-12-01 05:14:51 27 4
gpt4 key购买 nike

我可以使用 HTTP post 和响应检索 xml 文件。但是,现在我需要发布一个 String 参数以及 URL。以下代码告诉我 HTTP 状态代码不正常(即 500),因此它返回 null,然后我得到一个 NullPointerException

package com.JobsWebService;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import android.util.Log;

public class XmlConnection {

private static final String url = "http://www.accuservlite.com/AccumobileWS/TestService.asmx/RyanMB_GetJobs";
private DefaultHttpClient client = new DefaultHttpClient();
String param= "Johnny";

public List<NewJob> RyanMB_GetJobs() {
try {
String xmlData = retrieve(url);
Serializer serializer = new Persister();
Reader reader = new StringReader(xmlData);
ArrayOfNewJob testService = serializer.read(ArrayOfNewJob.class,
reader, false);
Log.i("gary", "Worked");
return testService.NewJob;

} catch (Exception e) {
Log.i("gary", e.toString());
}
return null;
}

// method retrieve
public String retrieve(String url) throws UnsupportedEncodingException {

List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("Johnny", "Johhny"));

UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(qparams,
HTTP.UTF_8);

HttpPost getRequest = new HttpPost(url);

getRequest.setEntity(postEntity);

try {

HttpResponse getResponse = client.execute(getRequest);

final int statusCode = getResponse.getStatusLine().getStatusCode();

if (statusCode != HttpStatus.SC_OK) {

return null;
}

HttpEntity getResponseEntity = getResponse.getEntity();

if (getResponseEntity != null) {
return EntityUtils.toString(getResponseEntity);
}

} catch (IOException e) {
Log.i("gary", "Error for URL " + url, e);
getRequest.abort();
}
return null;
}

}

最佳答案

500 是一个服务器错误,我觉得这段代码没有明显的错误。您是否针对 post 请求测试了服务器?当您向服务器提供名称值对时,服务器是否需要字符串?

您可以尝试使用 Wfetch 进行测试.

关于java - 如何从 Android 将参数发布到 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11417888/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com