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);
}
}
}
Related
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
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 construct the JSON Object
JSONObject jsonobj = new JSONObject();
JSONObject geoJsonObj = new JSONObject();
try {
jsonobj.put("action","put-point");
geoJsonObj.put("lng", longitude);
geoJsonObj.put("lat", latitude);
geoJsonObj.put("rangeKey", rangeKey);
geoJsonObj.put("schoolName", "TESTSCHOOL535353");
jsonobj.put("request", geoJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
I Execute an AsyncTask
new HTTPtoServer().execute(jsonobj);
The AsyncTask looks like this:
private class HTTPtoServer extends AsyncTask<JSONObject, Void, String> {
#Override
protected String doInBackground(JSONObject... params) {
//Prepare HTTP Post Client
DefaultHttpClient myClient = new DefaultHttpClient();
HttpPost myPost = new HttpPost(ElasticBeanStalkEndpoint);
StringEntity se = null;
Log.v("TEST","TEST");
try {
se = new StringEntity(params[0].toString());
Log.v("MY SE", se.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
myPost.setEntity(se);
HttpResponse httpresponse = null;
try {
httpresponse = myClient.execute(myPost);
} catch (IOException e) {
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(httpresponse.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
return responseText;
}
#Override
protected void onPostExecute(String s) {
Log.v("MY STRING", s);
}
}
However my JSON Object appears to never be "sending"?
Or maybe it is, but in an incorrect format?
The Java Tomcat server doesn't seem to be doing anything with the data?
My StringEntity results in :
org.apache.http.entity.StringEntity#528111f8
When I do se.toString()... Is this correct?
I seem to be a bit confused.
SERVER CODE:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
try {
StringBuffer buffer = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject jsonObject = new JSONObject(buffer.toString());
PrintWriter out = response.getWriter();
String action = jsonObject.getString("action");
log("action: " + action);
JSONObject requestObject = jsonObject.getJSONObject("request");
log("requestObject: " + requestObject);
if (action.equalsIgnoreCase("put-point")) {
putPoint(requestObject, out);
} else if (action.equalsIgnoreCase("get-point")) {
getPoint(requestObject, out);
} else if (action.equalsIgnoreCase("update-point")) {
updatePoint(requestObject, out);
} else if (action.equalsIgnoreCase("query-rectangle")) {
queryRectangle(requestObject, out);
} else if (action.equalsIgnoreCase("query-radius")) {
queryRadius(requestObject, out);
} else if (action.equalsIgnoreCase("delete-point")) {
deletePoint(requestObject, out);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
log(sw.toString());
}
}
private void putPoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException {
GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng"));
AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(UUID.randomUUID().toString());
AttributeValue schoolNameKeyAttributeValue = new AttributeValue().withS(requestObject.getString("schoolName"));
PutPointRequest putPointRequest = new PutPointRequest(geoPoint, rangeKeyAttributeValue);
putPointRequest.getPutItemRequest().addItemEntry("schoolName", schoolNameKeyAttributeValue);
PutPointResult putPointResult = geoDataManager.putPoint(putPointRequest);
printPutPointResult(putPointResult, out);
}
Try like that.
JSONObject jsonobj = new JSONObject();
JSONObject geoJsonObj = new JSONObject();
try {
jsonobj.put("action","put-point");
geoJsonObj.put("lng", longitude);
geoJsonObj.put("lat", latitude);
geoJsonObj.put("rangeKey", rangeKey);
geoJsonObj.put("schoolName", "TESTSCHOOL535353");
jsonobj.put("request", geoJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
new SendData().execute(jsonobj.toString());
public class SendData extends AsyncTask<String, Integer, Double>{
String response="";
#Override
protected Double doInBackground(String... params) {
postData(params[0]);
}
public void postData(String jsondata) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost=new HttpPost("url");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json",jsondata));
httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse res = httpclient.execute(httpPost);
InputStream content = res.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
System.out.println("response from server"+response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
SERVER SIDE-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsondata=request.getParameter("json");
//now parse your data from json
try {
JSONObject JsonObject=new JSONObject(jsondata);
JSONObject object=JsonObject.getJSONObject("request");
String action=object.getString("action");
String lng=object.getString("lng");
String lat=object.getString("lat");
String rangeKey=object.getString("rangeKey");
String schoolName=object.getString("schoolName");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I hope this will help you...!
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(PROJECT_ID, params[0]));
nameValuePairs.add(new BasicNameValuePair(BROKER_ID,params[1]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
StringBuilder responseJsonStr = new StringBuilder();
while ((output = br.readLine()) != null) {
responseJsonStr.append(output);
}
String queryString = Utils.getQueryString(nameValuePairs);
System.out.println("Query String "+URL +"&"+queryString);
//System.out.println("response Json String "+responseJsonStr );
if(!StringUtils.startsWith(responseJsonStr.toString(), "[")) {
responseJsonStr.insert(0,"[");
responseJsonStr.append("]");
}
try this:
public String getJson(Context applicationContext,String url) {
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("response_key",PrefernceSettings.getRestKey()));
nameValuePair.add(new BasicNameValuePair("response_request","auto_payments"));
Log.e("",String.valueOf(nameValuePairs));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
if(is != null){
result = convertInputStreamToString(is);
Log.e("result", result);
}else{
result = "Did not work!";
}
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
public String convertInputStreamToString(InputStream inputStream) {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
try {
while((line = bufferedReader.readLine()) != null)
result += line;
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
Try using this function:
public boolean postJSON(JSONObject jsonobj) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost("YOUR URL HERE");
StringEntity se = new StringEntity(jsonobj.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
httpPostRequest.setHeader("Accept-Encoding", "gzip");
//Send Http request
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
HttpEntity entity = response.getEntity();
String resonseStr = EntityUtils.toString(entity);
return getResponse(resonseStr);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
0D
where getResponse is a function that gets the response string and parses it and returns true or false according to how you define the web service.
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;
}
}
I'm working on an android project and I'm trying to get the text that a user enters in an EditText box and add it into an SQL table on my server. I think the problem is coming from not having the correct SQL query but I'm not sure what it is I have to add (I'm clueless when it comes to SQL) :S
When I run this app on my phone, it seems acknowledges that I have entered something and passed it to the database (no errors or exceptions appear) but nothing actually gets added to the database table.
Any ideas on where I went wrong would be appreciated!
JDBC Server Code:
public class DBServlet4 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/cs2001", "l2g0",
"l2g0");
stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS Students (id int, name varchar(45))");
stmt.executeUpdate("INSERT INTO Students (id, name) SELECT * FROM (SELECT '0', 'Michael') AS Temp WHERE NOT EXISTS (SELECT name FROM Students WHERE name = 'Michael') LIMIT 1");
//con.commit();
} catch (SQLException e) {
throw new ServletException(e.getMessage());
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (SQLException e) {
}
}
out.close();
}}
Android Code:
public class MainActivity extends Activity{
private static final String ipAddress = "172.31.81.28";
private static final String portNumber = "8085";
protected TextView getText;
protected EditText inputName;
protected List<Student> students;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getText = (TextView) findViewById(R.id.select_output);
inputName = (EditText) findViewById(R.id.name_input);
}
public void onClick(View v)
{
switch (v.getId())
{
case R.id.post_button:
{
//
String responseString = "";
try
{
responseString = new HttpPostTask().execute("" + inputName.getText()).get(10, TimeUnit.SECONDS);
}
catch (InterruptedException e)
{
responseString = "#An Error Occured: InterruptedException";
e.printStackTrace();
}
catch (TimeoutException e)
{
responseString = "#An Error Occured: TimeoutException";
e.printStackTrace();
}
catch (ExecutionException e)
{
responseString = "#An Error Occured: ExecutionException";
e.printStackTrace();
}
if (responseString.startsWith("#"))
{
Toast.makeText(this,
responseString.substring(1), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this,
responseString, Toast.LENGTH_SHORT).show();
}
break;
}
//code for getting data from DB
case R.id.get_button:
{
String responseString = "";
try
{
responseString = new HttpGetTask().execute("").get(10, TimeUnit.SECONDS);
}
catch (InterruptedException e)
{
responseString = "#An Error Occured: InterruptedException";
e.printStackTrace();
}
catch (TimeoutException e)
{
responseString = "#An Error Occured: TimeoutException";
e.printStackTrace();
}
catch (ExecutionException e)
{
responseString = "#An Error Occured: ExecutionException";
e.printStackTrace();
}
if (responseString.startsWith("#"))
{
Toast.makeText(this,
responseString.substring(1), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this,
"Connection Successful", Toast.LENGTH_SHORT).show();
this.getText.setText(responseString);
this.students = parseData(responseString, "\n", ":");
int i = 0;
for (Student student : students)
{
++i;
System.out.print("[" + i + "] " + student + "\n");
}
}
break;
}
default:
{
/* Do Nothing */
}
}
}
private List<Student> parseData(String input, String caseDelimiter, String fieldDelimiter)
{
String[] temp = input.split(caseDelimiter);
LinkedList<Student> students = new LinkedList<Student>();
for (int i = 0; i < temp.length; i++)
{
String[] tempStudent = temp[i].split(fieldDelimiter);
students.add(new Student(Integer.parseInt(tempStudent[0]), tempStudent[1].trim()));
}
return students;
}
private class Student
{
int id;
String name;
public Student(int id, String name)
{
this.id = id;
this.name = name;
}
public String toString()
{
return "" + id + " - " + name;
}
}
private class HttpPostTask extends AsyncTask<String, Integer, String>
{
private static final String ipAddress = "172.31.81.28"; // *** UPDATE THIS ***
private static final String portNumber = "8085"; // *** UPDATE THIS ***
#Override
protected String doInBackground(String... args)
{
String responseString = "An Unknown Error Occured";
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
String url = "http://" + ipAddress + ":" + portNumber + "/DB4";
HttpPost request = new HttpPost(url);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("username", args[0]));
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
HttpEntity resEntityGet = response.getEntity();
if (resEntityGet != null)
{
responseString = EntityUtils.toString(resEntityGet);
}
}
catch (ClientProtocolException e)
{
responseString = "#An Error Occured: ClientProtocolException";
e.printStackTrace();
}
catch (IOException e)
{
responseString = "#An Error Occured: IOException";
e.printStackTrace();
}
return responseString;
}
}
private class HttpGetTask extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... args)
{
String url = "http://172.31.81.28:8085/DB4";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
String responseString = "";
try
{
HttpResponse response = client.execute(request);
HttpEntity resEntityGet = response.getEntity();
if (resEntityGet != null)
{
responseString = EntityUtils.toString(resEntityGet);
}
}
catch (Exception e)
{
responseString = "#An Error Occured: UndeclaredException";
e.printStackTrace();
}
return responseString;
}
}
}
Nevermind, problem solved. I used a separate AsyncTask class.