HttpClient.execute上的java.lang.NullPointerException
在使用Junit运行单元测试时,我一直在努力解决这个错误。(更多的是集成测试,因为其目的是检查库是否返回响应)。但我得到了以下错误:HttpClient.execute上的java.lang.NullPointerException,java,android,apache,junit,httpclient,Java,Android,Apache,Junit,Httpclient,在使用Junit运行单元测试时,我一直在努力解决这个错误。(更多的是集成测试,因为其目的是检查库是否返回响应)。但我得到了以下错误: java.lang.NullPointerException at com.alliancetech.util.RestClient.execute(RestClient.java:84) at com.alliancetech.atdroidnetworklib.ITAssociationsAPI.testAssociationsByEventI
java.lang.NullPointerException
at com.alliancetech.util.RestClient.execute(RestClient.java:84)
at com.alliancetech.atdroidnetworklib.ITAssociationsAPI.testAssociationsByEventID(ITAssociationsAPI.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
RestClient.execute正在调用HttpClient的execute方法,但是响应对象始终为null
我是Junit新手,从未使用它进行过集成测试。我看了看是否可能,它说是的,但现在我不确定
以下是我的测试代码:
public class ITAssociationsAPI extends ITLeadsRestTest {
@Before
public void setup(){}
@Test
public void testAssociationsByEventID(){
String urlGetAssociationsById = API_URL + "rest of the url";
RestClient rcAssociationsByEventID = new RestClient(urlGetAssociationsById);
// Checks if the http code was 200.
int code = rcAssociationsByEventID.execute();
assertEquals(200, code);
// Checks if the response is not null
JSONObject content = rcAssociationsByEventID.getJSONResponse();
assertNotNull(content);
// Checks if the content is a JSON body
boolean valid = isContentJSON(content);
assertEquals(true, valid);
}
}
public abstract class ITLeadsRestTest extends TestCase{
protected final String API_URL = "*******";
protected boolean isContentJSON(JSONObject content){
boolean valid = false;
JSONObject validator = content;
return valid;
}
}
如能对此有所了解,将不胜感激
编辑
以下是RestClient代码:
public class RestClient {
private static final String TAG = "RestClient";
private String url;
private HttpResponse response;
private JSONObject body = null;
private ArrayList<NameValuePair> params;
protected RestClient(){}
public static class RestClientException extends RuntimeException
{
public RestClientException( Exception exc )
{
super(exc);
}
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
}
public void addQueryParam( String name, String value )
{
params.add(new BasicNameValuePair(name, value));
}
public void setBody( JSONObject jsonObj )
{
this.body = jsonObj;
}
public int execute()
{
HttpClient client = new DefaultHttpClient();
String uri = null;
try {
uri = (params.isEmpty())? url : url + getParams();
} catch (UnsupportedEncodingException e) {
uri = url;
}
try {
response = client.execute(new HttpGet(uri));
StatusLine status =response.getStatusLine();
int result = status.getStatusCode();
return result;
} catch (IOException e) {
throw new RestClientException(e);
}
}
public JSONObject getJSONResponse()
{
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
return (JSONObject) JSONValue.parse(out.toString());
} catch (IOException e) {
throw new RestClientException(e);
}
}
public JSONArray getJSONResponseArray()
{
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
return (JSONArray) JSONValue.parse(out.toString());
} catch (IOException e) {
throw new RestClientException(e);
}
}
private final String getParams()
throws UnsupportedEncodingException {
StringBuffer combinedParams = new StringBuffer();
if (!params.isEmpty()) {
combinedParams.append("?");
for (NameValuePair p : params) {
combinedParams.append((combinedParams.length() > 1 ? "&" : "")
+ p.getName() + "="
+ URLEncoder.encode(p.getValue(), "UTF-8"));
}
}
return combinedParams.toString();
}
public final int executePost(File inputFile) {
HttpClient client = new DefaultHttpClient();
String uri = null;
try {
uri = (params.isEmpty())? url : url + getParams();
} catch (UnsupportedEncodingException e) {
uri = url;
}
try {
HttpPost post = new HttpPost(uri);
post.addHeader("Content-Type", "application/json");
// FileEntity entity = new FileEntity( inputFile, "application/json" );
InputStreamEntity entity = new InputStreamEntity( new FileInputStream(inputFile), inputFile.length());
post.setEntity( entity );
response = client.execute( post );
StatusLine status =response.getStatusLine();
int result = status.getStatusCode();
Log.d(TAG, "POST RESULT: " + result + "(" + status.getReasonPhrase() + ")");
return result;
} catch (IOException e) {
throw new RestClientException(e);
}
}
public final int executePost() {
HttpClient client = new DefaultHttpClient();
String uri = null;
try {
uri = (params.isEmpty())? url : url + getParams();
} catch (UnsupportedEncodingException e) {
uri = url;
}
try {
HttpPost post = new HttpPost(uri);
post.addHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity( body.toJSONString(), "UTF-8" );
post.setEntity( entity );
response = client.execute( post );
StatusLine status =response.getStatusLine();
int result = status.getStatusCode();
Log.d(TAG, "POST RESULT: " + result + "(" + status.getReasonPhrase() + ")");
return result;
} catch (IOException e) {
throw new RestClientException(e);
}
}
public final InputStream contentStream() {
try {
return response.getEntity().getContent();
} catch (IOException e) {
throw new RestClientException(e);
}
}
公共类RestClient{
私有静态最终字符串TAG=“RestClient”;
私有字符串url;
私有HttpResponse响应;
私有JSONObject body=null;
私有数组列表参数;
受保护的RestClient(){}
公共静态类RestClientException扩展了RuntimeException
{
公共RestClientException(例外exc)
{
超级(行政会议);;
}
}
公共RestClient(字符串url)
{
this.url=url;
params=新的ArrayList();
}
public void addQueryParam(字符串名称、字符串值)
{
添加(新的BasicNameValuePair(名称、值));
}
公共对象(JSONObject jsonObj)
{
this.body=jsonObj;
}
公共int执行()
{
HttpClient=new DefaultHttpClient();
字符串uri=null;
试一试{
uri=(params.isEmpty())?url:url+getParams();
}捕获(不支持的编码异常e){
uri=url;
}
试一试{
response=client.execute(新的HttpGet(uri));
StatusLine status=response.getStatusLine();
int result=status.getStatusCode();
返回结果;
}捕获(IOE异常){
抛出新的RestClientException(e);
}
}
公共JSONObject getJSONResponse()
{
试一试{
ByteArrayOutputStream out=新建ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
return(JSONObject)JSONValue.parse(out.toString());
}捕获(IOE异常){
抛出新的RestClientException(e);
}
}
公共JSONArray getJSONResponseArray()
{
试一试{
ByteArrayOutputStream out=新建ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
return(JSONArray)JSONValue.parse(out.toString());
}捕获(IOE异常){
抛出新的RestClientException(e);
}
}
私有最终字符串getParams()
抛出不支持的DencodingException{
StringBuffer combinedParams=新的StringBuffer();
如果(!params.isEmpty()){
组合参数追加(“?”);
用于(名称值对p:params){
combinedParams.append((combinedParams.length()>1?&):“”)
+p.getName()+“=”
+encode(p.getValue(),“UTF-8”);
}
}
返回combinedParams.toString();
}
公共最终int executePost(文件输入文件){
HttpClient=new DefaultHttpClient();
字符串uri=null;
试一试{
uri=(params.isEmpty())?url:url+getParams();
}捕获(不支持的编码异常e){
uri=url;
}
试一试{
HttpPost=新的HttpPost(uri);
post.addHeader(“内容类型”、“应用程序/json”);
//FileEntity=新的FileEntity(输入文件,“应用程序/json”);
InputStreamEntity实体=新的InputStreamEntity(新文件InputStream(inputFile),inputFile.length());
后设实体(实体);
响应=client.execute(post);
StatusLine status=response.getStatusLine();
int result=status.getStatusCode();
Log.d(标记“POST RESULT:+RESULT+”(“+status.getReasonPhrase()+”);
返回结果;
}捕获(IOE异常){
抛出新的RestClientException(e);
}
}
公共最终int executePost(){
HttpClient=new DefaultHttpClient();
字符串uri=null;
试一试{
uri=(params.isEmpty())?url:url+getParams();
}捕获(不支持的编码异常e){
uri=url;
}
试一试{
HttpPost=新的HttpPost(uri);
post.addHeader(“内容类型”、“应用程序/json”);
StringEntity实体=新的StringEntity(body.toJSONString(),“UTF-8”);
后设实体(实体);
响应=client.execute(post);
StatusLine status=response.getStatusLine();
int result=status.getStatusCode();
Log.d(标记“POST RESULT:+RESULT+”(“+status.getReasonPhrase()+”);
返回结果;
}捕获(IOE异常){
抛出新的RestClientException(e);
}
}
公共最终输入流contentStream(){
试一试{
返回response.getEntity().getContent();
}捕获(IOE异常){
抛出新的RestClientException(e);
}
}
}您说您正在检查响应是否为空,但您的代码告诉我,即使响应为空,您仍在继续使用
assertEquals()
。我想知道你为什么会得到NPE…你也能提供RestClient类代码吗?Vin我发布了RestClient的代码。哪一行是RestClient.java:84
?在方法execute中,这一行是:response=client.execute(new-HttpGet(uri));