I am try to make a tiny util so that I can send a HttpRequest repeatedly and I use HttpClient to do this.
But I have a problem, I can not send HttpRequest in circulation. To more detail, it can sent request at first cycle, but after that it can not send request and the thread is waiting at there.
there is the main code:
for (int i = 0; i < 10; i++) {
HttpResponse result = Launcher.bulider()
.setCharSet("utf-8")
.setHttpMethod("GET")
.setUrl("http://www.baidu.com")
.fullResponse();
System.out.println(result.getStatusLine().getStatusCode());
}
Launcher.java:
public abstract class Launcher {
public static class bulider{
private String httpMethod;
private String url;
private Map<String, String> params;
private String charSet;
private Class type;
public bulider setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
return this;
}
public bulider setUrl(String url) {
this.url = url;
return this;
}
public bulider setParams(Map<String, String> params) {
this.params = params;
return this;
}
public bulider setCharSet(String charSet) {
this.charSet = charSet;
return this;
}
public String data() {
if (httpMethod.equalsIgnoreCase(HttpMethod.GET)){
return HttpTemplate.doGet(this.url,this.params,this.charSet);
}
if (httpMethod.equalsIgnoreCase(HttpMethod.POST)){
return HttpTemplate.doPost(this.url,this.params,this.charSet);
}
return null;
}
public <T> T jsonObject(Class<T> type) {
if (httpMethod.equalsIgnoreCase(HttpMethod.GET)) {
return HttpTemplate.getReObj(type, this.url, this.params, this.charSet);
}
if (httpMethod.equalsIgnoreCase(HttpMethod.POST)) {
return HttpTemplate.postReObj(type, this.url, this.params, this.charSet);
}
return null;
}
public HttpResponse fullResponse() {
if (httpMethod.equalsIgnoreCase(HttpMethod.GET)) {
return HttpTemplate.getReResponse(this.url, this.params, this.charSet);
}
if (httpMethod.equalsIgnoreCase(HttpMethod.POST)) {
return HttpTemplate.postReResponse(this.url, this.params, this.charSet);
}
return null;
}
}
public static bulider bulider(){
return new bulider();
}
}
HttpTemplate.java:
public class HttpTemplate {
private static final Logger logger = LoggerFactory.getLogger(HttpTemplate.class);
private static final CloseableHttpClient httpClient;
public static final String DEFAULT_CHARSET = "utf-8";
static {
RequestConfig config = RequestConfig.custom().setConnectTimeout(6000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
public static String doGet(String url, Map<String, String> param, String charset) {
try {
HttpGet httpGet = (HttpGet) initRequestParam("Get", url, param, charset);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (!String.valueOf(statusCode).startsWith("2")) {
throw new RuntimeException("Http Template Error :: status code " + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String doPost(String url, Map<String, String> params, String charset) {
try {
HttpPost httpPost = (HttpPost) initRequestParam("Post", url, params, charset);
HttpResponse response = httpClient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
if (!String.valueOf(status).startsWith("2")) {
throw new RuntimeException("Http Template Error :: status error " + status);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity);
}
EntityUtils.consume(entity);
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> T getReObj(Class<T> type, String url, Map<String, String> param, String charset) {
try {
HttpGet httpGet = (HttpGet) initRequestParam("Get", url, param, charset);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (!String.valueOf(statusCode).startsWith("2")) {
throw new RuntimeException("Http Template Error :: status code " + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
logger.info(result);
EntityUtils.consume(entity);
T resultNew = JSON.parseObject(result, type);
logger.info(resultNew.getClass().toString());
return resultNew;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> T postReObj(Class<T> type, String url, Map<String, String> params, String charset) {
try {
HttpPost httpPost = (HttpPost) initRequestParam("Post", url, params, charset);
HttpResponse response = httpClient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
if (!String.valueOf(status).startsWith("2")) {
throw new RuntimeException("Http Template Error :: status error " + status);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
T resultNew = JSON.parseObject(result, type);
return resultNew;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static HttpResponse getReResponse(String url, Map<String, String> param, String charset) {
try {
HttpGet httpGet = (HttpGet) initRequestParam("Get", url, param, charset);
return httpClient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static HttpResponse postReResponse(String url, Map<String, String> param, String charset) {
try {
HttpPost httpPost = (HttpPost) initRequestParam("Post", url, param, charset);
return httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static HttpRequestBase initRequestParam(String methodName, String url, Map<String, String> params, String charset) {
logger.info(url);
if (!StringKit.isNotBlank(url)) {
return null;
}
if (null == charset) {
charset = DEFAULT_CHARSET;
}
List<NameValuePair> pairList = null;
if (params != null && !params.isEmpty()) {
pairList = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairList.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
if ("Get".equalsIgnoreCase(methodName)) {
try {
if (pairList != null) {
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairList, charset));
}
logger.info(url);
HttpGet httpGet = new HttpGet(url);
return httpGet;
} catch (IOException e) {
e.printStackTrace();
}
} else if ("Post".equalsIgnoreCase(methodName)) {
try {
HttpPost httpPost = new HttpPost(url);
if (pairList != null && !pairList.isEmpty()) {
httpPost.setEntity(new UrlEncodedFormEntity(pairList));
}
return httpPost;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>httpLaunch</groupId>
<artifactId>httpLaunch</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--http client-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
there is the whole code:https://github.com/vzardlloo/http-launcher
Related
I know the apache library is deprecated, but I was wondering if it is possible to send the string "ansi" in this code to a PHP script on a server at a URL. My code is below and I don't know what I'm missing.
Any help would be appreciated.
I've looked up a lot online and many people suggest using StringEntity, which I did, but it's still not working :/
I'm trying to retrieve a lot of data from the PHP but the PHP script needs the string "ansi" before data can be retrieved.
public class HttpServiceClass {
private ArrayList<NameValuePair> params;
private ArrayList<NameValuePair> headers;
private String ansi;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public HttpServiceClass(String url, String ansi) {
this.url = url;
this.ansi = ansi;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value) {
headers.add(new BasicNameValuePair(name, value));
}
public void ExecuteGetRequest() throws Exception {
String combinedParams = "";
if (!params.isEmpty()) {
combinedParams += "?";
for (NameValuePair p : params) {
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8");
if (combinedParams.length() > 1) {
combinedParams += "&" + paramString;
} else {
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
for (NameValuePair h : headers) {
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url, ansi);
}
public void ExecutePostRequest() throws Exception {
HttpPost request = new HttpPost(url);
request.setEntity(new StringEntity(ansi));
for (NameValuePair h : headers) {
request.addHeader(h.getName(), h.getValue());
}
if (!params.isEmpty()) {
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url, ansi);
}
private void executeRequest(HttpUriRequest request, String url, String ansi) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I don't know how I can set a header "Accept" for 'applicatjon/json now my response from server is a xml but I want to have a json. A server should send me a xml when I set a header. This is my code :
final JSONObject requestObject = new JSONObject();
try {
requestObject.put("company", "TEST");
requestObject.put("user", "pawelo");
requestObject.put("secure_password", "8ce241e1ed84937ee48322b170b9b18c");
requestObject.put("secure_device_id", "C4CA4238A0B923820DCC509A6F75849B");
} catch (JSONException e) {
e.printStackTrace();
}
StringEntity entity = null;
try {
entity = new StringEntity(requestObject.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(this, url, entity, "application/json",
new BaseJsonHttpResponseHandler("UTF-8") {
#Override
public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) {
Log.e("sdasa " , rawJsonResponse + " " + statusCode);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {
}
#Override
protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
return null;
}
});
JSONObject json = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("body", message);
dataJson.put("title", getFirebaseUser().getDisplayName());
json.put("notification", dataJson);
json.put("registration_ids",jsonArray);
StringEntity se = new StringEntity(json.toString(), "UTF-8");
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json;charset=utf-8");
client.addHeader("Authorization", "key=" + "xxxxxxxxxxxx");
client.post(getInstance(), "your url", se, "application/json;charset=utf-8", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.e("success_noti", new String(responseBody) + "");
if(isEnd){
getMessage.getMessageFunc(END);
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("fail_noti", new String(responseBody) + "");
}
});
Using AsyncHttpClient Library This is also another approach.
You can Add accept line on header when you are sending request to server.
URL url;
HttpURLConnection urlConnection = null;
String response = null;
InputStream in = null;
try {
url = new URL(urlStr);
urlConnection = (HttpURLConnection) url.openConnection();
/* optional request header */
urlConnection.setRequestProperty("Content-Type", "application/json");
/* optional request header */
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("GET");
//InputStream in = urlConnection.getInputStream();
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
in = new BufferedInputStream(urlConnection.getInputStream());
response = Utils.convertInputStreamToString(in);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
use this code
public String POST(String url, Been been){
InputStream inputStream = null;
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("company", Been.getcompany());
jsonObject.accumulate("user", Been.getuser());
jsonObject.accumulate("secure_password", Been.getpassword());
jsonObject.accumulate("secure_device_id", Been.getdevice_id());
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse1 = httpclient.execute(httpPost);
inputStream = httpResponse1.getEntity() .getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
use AsyncTask to call method
public class HttpAsyncTask extends AsyncTask<Void, Void, String> {
private ProgressDialog mProgressDialog;
private DefaultHttpClient httpclient;
private HttpPost httppost;
#Override
protected String doInBackground(Void... params) {
httpclient = new DefaultHttpClient();
//Create new HTTP POST with URL to php file as parameter
httppost = new HttpPost(url);
Been = new Been();
Been.setcompany("TEST");
Been.setuser("pawelo");
Been.setpassword("8ce241e1ed84937ee48322b170b9b18c");
Been.setdevice_id("C4CA4238A0B923820DCC509A6F75849B");
return POST(url, Been);
}
#Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(getActivity(), "", "loading...");
mProgressDialog.setCancelable(false);
mProgressDialog.setCanceledOnTouchOutside(false);
}
}
Create Boon class
public class Been {
private String name;
private String user;
private String password;
private String device_id;
public String getcompany() {
return name;
}
public void setcompany(String name1) {
this.name= name1;
}
public String getuser() {
return user;
}
public void setuser(String user1) {
this.user= user1;
}
public String getpassword() {
return user;
}
public void setpassword(String password1) {
this.password= password1;
}
public String getdevice_id() {
return user;
}
public void setdevice_id(String device_id1) {
this.device_id= device_id1;
}
}
i want to get data from my server with AsyncTask and then extract some and send to another location and get more info from that
for first section I'm using from this code for run my AsyncTask method and Cancel AsyncTask after some time (for no response...)
new MySecendServer(link, param,mInstagramSession).execute();
final ProgressDialog pd2 = new ProgressDialog(testActivity.this);
pd2.show();
final Timer tm = new Timer();
tm.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
count++;
if (count == 30) {
pd2.cancel();
tm.cancel();
new MySecendServer(.....) .cancel(true); }
}
});
}
}, 1, 1000);
then after get data from my server i try to get more info with this code but i don't get any response or exception i test this code in doInBackground And onPostExecute and no any diffrent and no any response
try {
String requestUrl = "https://api.instagram.com/v1/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(requestUrl);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
throw new Exception("Request returns empty result");
}
InputStream stream = httpEntity.getContent();
String response = StringUtil.streamToString(stream);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new Exception(httpResponse.getStatusLine().getReasonPhrase());
}
} catch (Exception ex) {}
now anyone can give me reason or any suggest for do this work ?
thanks
Update :
I found exception here :
HttpResponse httpResponse = httpClient.execute(httpGet);
and message is :
cause NetworkOnMainThreadException (id=831620140512)
Update 2 :
My first AsyncTask
public class MySecendServerClass extends AsyncTask {
private String link="";
private String [][]pparams;
private InstagramUser IG_User;
private InstagramSession IG_Session;
public MySecendServerClass(String link,String [][]params,InstagramSession user){
this.link=link;
this.pparams=params;
this.IG_Session = user;
}
#Override
protected String doInBackground(Object... arg0) {
String data="";
try{
if(pparams!=null){
for(int i=0;i<pparams.length;i++){
if(i!=0){
data+="&";
}
data+=URLEncoder.encode(pparams[i][0],"UTF8")+"="+URLEncoder.encode(pparams[i][1],"UTF8");
}
}
URL mylink=new URL(link);
URLConnection connect=mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
sb.append(line);
}
Log.d("sssss",sb.toString());
return sb.toString();
}
catch(Exception ex){
}
return null;
}
#Override
protected void onPostExecute(Object tr) {
super.onPostExecute(tr);
String result = (String)tr;
try{
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("followlist");
JSONObject jObject = jArray.getJSONObject(0);
String client_id=jObject.getString("client_id");
GrtUserProfile(client_id);
}
catch(Exception ex){
}
}
}
Solve Problem With this Code :
public void GrtUserProfile(String Cid) {
String requestUrl= "https://api.instagram.com/v1/users/"+Cid+"/"+"&access_token="+mInstagramSession.getAccessToken();
new HTTPRequestClass().execute(requestUrl);
}
class HTTPRequestClass extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
try {
String url = urls[0];
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
throw new Exception("Request returns empty result");
}
InputStream stream = httpEntity.getContent();
String response = StringUtil.streamToString(stream);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new Exception(httpResponse.getStatusLine().getReasonPhrase());
}
return response;
} catch (Exception e) {
return "";
}
}
protected void onPostExecute(String Response) {
Log.i("Response", Response);
}
}
Instead of using Timer to cancel async task you can set timeout for HttpURLConnection
private class DownloadFilesTask extends AsyncTask<URL, Integer, Boolean> {
protected Boolean doInBackground(URL... urls) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000); //set timeout to 5 seconds
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
return false;
} catch (java.io.IOException e) {
return false;
}
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Boolean result) {
showDialog("Downloaded " + result );
}
}
I've been struggling with this error while running a Unit Test using Junit. (More an Integration test, because the idea is to check if the library is returning the response). But I'm getting the following error:
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 is calling HttpClient's execute method, however the response object is always a null.
I'm new to Junit and I have never done an Integration test using it. I looked if it was possible and it says it is, but right now I'm not sure.
Here is my test code:
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;
}
}
Any light on this would be greatly appreciated.
Edit
Here is the RestClient code:
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);
}
}
}
I need to good class for sending and handling the all request such as get , post
I researched anywhere but i could not find the good helper class for it , i am beginner in java and android , please share a good connection helper class with me
public class RRequestHelper
{
DefaultHttpClient httpClient;
HttpContext localContext;
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
public RRequestHelper()
{
this.setDefaultOptions();
}
public void setDefaultOptions()
{
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, RGeneralSettings.getInstance().getSettingInt(RConstants.CONNECTION_TIMEOUT, false));
HttpConnectionParams.setSoTimeout(myParams, RGeneralSettings.getInstance().getSettingInt(RConstants.CONNECTION_TIMEOUT, false));
httpClient = new DefaultHttpClient(myParams);
localContext = new BasicHttpContext();
}
public void clearCookies()
{
httpClient.getCookieStore().clear();
}
public void abort()
{
try
{
if (httpClient != null)
{
System.out.println("Abort.");
httpPost.abort();
}
}
catch (Exception e)
{
System.out.println("Your App Name Here" + e);
}
}
public String sendPost(String url, String data)
{
return sendPost(url, data, null);
}
public String sendJSONPost(String url, JSONObject data)
{
return sendPost(url, data.toString(), "application/json");
}
public String sendPost(String url, String data, String contentType)
{
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
Log.d("Your App Name Here", "Setting httpPost headers");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0");
httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
if (contentType != null)
{
httpPost.setHeader("Content-Type", contentType);
}
else
{
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
}
try
{
tmp = new StringEntity(data,"UTF-8");
}
catch (UnsupportedEncodingException e)
{
Log.e("Your App Name Here", "HttpUtils : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
Log.d("Your App Name Here", url + "?" + data);
try
{
response = httpClient.execute(httpPost,localContext);
if (response != null)
{
ret = EntityUtils.toString(response.getEntity());
}
}
catch (Exception e)
{
Log.e("Your App Name Here", "HttpUtils: " + e);
}
Log.d("Your App Name Here", "Returning value:" + ret);
return ret;
}
public String sendGet(String url) {
httpGet = new HttpGet(url);
try {
response = httpClient.execute(httpGet);
} catch (Exception e) {
Log.e("Your App Name Here", e.getMessage());
}
//int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
try {
ret = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
Log.e("Your App Name Here", e.getMessage());
}
return ret;
}
public InputStream getHttpStream(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
{
throw new IOException("Not an HTTP connection");
}
try
{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception e)
{
throw new IOException("Error connecting");
} // end try-catch
return in;
}
}