parsing json data in API url using jsonparser - java

I have a JSON data in this URL : http://api.pemiluapi.org/calonpresiden/api/caleg/jk?apiKey=56513c05217f73e6be82d5542368ae4f
when I try parsing using this jsonparser code :
package percobaan;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String makeHttpRequest(String url, String method) {
return this.makeHttpRequest(url, method, null);
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
is.close();
json = sBuilder.toString();
} catch (Exception exception) {
exception.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
}
// return JSON String
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public String makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
// check for request method
if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
// DefaultHttpClient httpClient = new
// DefaultHttpClient(httpParameters);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
}
// return JSON String
return json;
}
}
why the output just says :
{"data":[]}
this is my code :
package percobaan;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* #author nafian
*/
public class Coba {
public static void main(String[] args) {
ArrayList<HashMap<String, String>> daftar_d = new ArrayList<HashMap<String, String>>();
JSONParser jsonParser = new JSONParser();
String link_url = "http://api.pemiluapi.org/calonpresiden/api/caleg/jk?apiKey=56513c05217f73e6be82d5542368ae4f";
List<NameValuePair> params = new ArrayList<NameValuePair>();
String parsing = jsonParser.makeHttpRequest(link_url, "POST",
params);
System.out.print(parsing);
// try {
// JSONObject json = new JSONObject(parsing).getJSONObject("data").getJSONObject("results");
// JSONArray caleg = json.getJSONArray("caleg");
//
// for (int i = 0; i < caleg.length(); i++) {
// HashMap<String, String> map = new HashMap<String, String>();
// JSONObject ar = caleg.getJSONObject(i);
// String nama = ar.getString("nama");
// String calon = ar.getString("role");
//
// JSONArray riwayat = ar.getJSONArray("riwayat_pendidikan");
// for (int j = 0; j < riwayat.length(); j++) {
// JSONObject ringkasan = riwayat.getJSONObject(j);
// String ringkasan_p = ringkasan.getString("ringkasan");
// map.put("pendidikan_r", ringkasan_p);
// }
//
// map.put("nama", nama);
// map.put("calon", calon);
// daftar_d.add(map);
//
// }
// } catch (JSONException ex) {
// ex.printStackTrace();
// }
// for (int i = 0; i < daftar_d.size(); i++) {
//
// System.out.println(daftar_d.get(i).get("pendidikan_r").toString());
// }
}
}
Am I missing something?

I suggest you use JSON-SIMPLE, it will literally simplify your life.
https://code.google.com/p/json-simple/
Here is a small example for the given URL.
Please note that's I'm using Jersey for establishing the connection, but you can pretty much use anything you like instead.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
...
String callString = "http://api.pemiluapi.org/calonpresiden/api/caleg/jk?apiKey=56513c05217f73e6be82d5542368ae4f";
Client client = Client.create();
WebResource webResource = client.resource(callString);
ClientResponse clientResponse = webResource.accept("application/json").get(ClientResponse.class);
if (clientResponse.getStatus() != 200) {
throw new RuntimeException("Failed"+ clientResponse.toString());
}
JSONObject resObj = (JSONObject)new JSONParser().parse(clientResponse.getEntity(String.class));
JSONObject data_obj = (JSONObject) resObj.get("data");
JSONObject results_obj = (JSONObject) data_obj.get("results");
JSONArray caleg_array = (JSONArray) results_obj.get("caleg");

Related

Unable to receive any request from MSTeams to my endpoint

I created a bot using Bot Channels Registration and integrated it with the MSTeams channel. But when I send a message from Teams, I did not receive any request from the Teams to my Message Endpoint.
Please help me to resolve with this.
Please try using this.
TestSample.java
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
#WebServlet("/MSTeamsServlet/api/messages")
public class TestSample extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestSample() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletInputStream st = request.getInputStream();
JSONObject inputjson = new JSONObject();
JSONParser parser = new JSONParser();
String inputJson ="";
try {
BufferedInputStream bin = new BufferedInputStream(st);
int ch;
inputJson= "";
while ((ch = bin.read()) != -1) {
inputJson = inputJson+(char)ch;
}
} catch (Exception e) {
e.printStackTrace();
}
String result = "";
System.out.println("INSIDE MS TEAMS SERVLET:::");
System.out.println("REQUEST:"+inputJson);
JSONObject json = new JSONObject();
JSONParser parse = new JSONParser();
JSONObject requestBody = new JSONObject();
TestRequest client = new TestRequest();
try
{
requestBody = (JSONObject)parse.parse(inputJson);
JSONObject conversation = (JSONObject) requestBody.get("conversation");
String id = requestBody.get("id").toString();
String serviceUrl = requestBody.get("serviceUrl").toString();
String conversationId = conversation.get("id").toString();
JSONObject from = (JSONObject) requestBody.get("from");
JSONObject recepient = (JSONObject) requestBody.get("recipient");
String url = serviceUrl+"v3/conversations/"+conversationId+"/activities/"+id;
String userId = "";
String aadObjectId = from.get("aadObjectId").toString();
json.put("text", "Hai! How can I help you!!!");
json.put("type", "message");
json.put("from", recepient);
json.put("conversation", conversation);
json.put("recipient", from);
json.put("replyToId", id);
result = client.hitPOSTAPI(url, "POST", json);
System.out.println(result);
PrintWriter out = response.getWriter();
out.print(result);
out.flush();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
TestRequest.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.Charsets;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.common.io.CharStreams;
public class TestRequest {
static String microsoft_AppID = "REPLACE YOUR APP_ID";
static String microsoft_AppPwd = "REPLACE YOUR APP_PASSWORD";
public static String hitPOSTAPI(String urlString, String methodType, JSONObject postParameter) {
String result = "";
try {
HttpPost post = new HttpPost(urlString);
StringEntity params = new StringEntity(postParameter.toString());
System.err.println(postParameter.toString());
post.addHeader("content-type", "application/json");
post.addHeader("Authorization", "Bearer "+generateToken());
post.setEntity(params);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20 * 1000).setConnectionRequestTimeout(20*1000).setSocketTimeout(100*1000).build();
HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
HttpResponse response = httpClient.execute(post);
InputStream in = null;
if (response.getStatusLine().getStatusCode()==200 &&response != null) {
in = response.getEntity().getContent();
result = CharStreams.toString(new InputStreamReader(
in, Charsets.UTF_8));
}
post.abort();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
}
return result;
}
public static String generateToken() {
String token = "";
URL url = null;
HttpURLConnection urlConnection = null;
String result = "";
try {
url = new URL("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setRequestProperty("Host", "login.microsoftonline.com");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
OutputStream wr = urlConnection.getOutputStream();
String credentials = "grant_type=client_credentials&client_id="+microsoft_AppID+"&client_secret="+microsoft_AppPwd+"&scope=https://api.botframework.com/.default";
wr.write(credentials.toString().getBytes());
wr.flush();
wr.close();
if(urlConnection.getResponseCode()==200)
{
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader isReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while((str = reader.readLine())!= null){
sb.append(str);
}
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject)parser.parse(sb.toString());
token = obj.get("access_token").toString();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
urlConnection.disconnect();
}
return token;
}
}
Please check this are you able to get any idea. As for MSTeams only my endpoint is not working..If I check it through NGROK it is working.

update/create JSON object on button press

im am currently creating a CMS applicationa and i am trying to create a JSON object that i can post to my API but i have no idea on how to do this because im new to android. does anyone have an Idea?
My code:
String URL = "http://test.soundwave.drieo.nl/api/content/" + uid + "?apikey=aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
try {
APIClientJSONObject api = new APIClientJSONObject();
JSONObject result = null;
try {
result = api.execute(URL).get();
} catch (Exception e) {
e.printStackTrace();
}
try {
String content = result.optString("FormattedName");
String content2 = result.optString("Title");
String content3 = result.optString("Subtitle");
String content4 = result.optString("Text");
EditText name = (EditText) findViewById(R.id.etInternNaam);
name.setText(content);
EditText titel = (EditText) findViewById(R.id.etName);
titel.setText(content2);
EditText ondertitel = (EditText) findViewById(R.id.etOndertitel);
ondertitel.setText(content3);
EditText EditText = (EditText) findViewById(R.id.etTekst);
EditText.setText(Html.fromHtml(content4));
if("null" == content) {
name.setText("");
}
if("null" == content2) {
titel.setText("");
}
if("null" == content3) {
ondertitel.setText("");
}
if("null" == content4) {
EditText.setText("");
}
} catch (Exception e) {
e.printStackTrace();
}
API code:
package nl.drieo.soundwave.test.cms;
import android.os.AsyncTask;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
/**
* Created by r.devries on 14-3-2016.
*/
public class APIClientJSONObject extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... params) {
JSONObject result = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = new JSONObject(builder.toString());
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
you can create JSONObject like this and put your data into that:
JSONObject json = new JSONObject();
json.put("user", "example");
after putting your data to json, you can pass the json to the 'APIClientJSONObject' class by this way:
EDIT: use this code in to OnClickListener for your Button
try {
result = api.execute(URL,json.toString()).get();
} catch (Exception e) {
e.printStackTrace();
}
and you can get Json in 'APIClientJSONObject' class like this:
JSONObject jsonObject = new JSONObject(params[1])
or if you want 'POST' this json to the webservice, you can use: EDIT: use this in to the APIClientJSONObject class in doInBackground method:
HttpPost httpost = new HttpPost(params[0]);
StringEntity stringentity = new StringEntity(params[1]);
httpost.setEntity(stringentity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
httpclient.execute(httpost, responseHandler);
I hope these code are useful for you.

ServiceHandler class returns null value

Here is code and response is null. How can I solve this?
I want to talk with server for login but JSON response shows null value. I want to insert data into database and fetch data from database there is connection is proper because output URL is proper and by that URL I can insert data but from device it is not working.
package com.example.old_login;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class ServiceHandler {
public final static int GET = 1;
public final static int POST = 2;
static String response = null;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}

Warning/Error meaning - GbaRequest - GbaRequest: Constructor Called 222 userAgent Apache-HttpClient/UNAVAILABLE

W/System.err(27207): [DEBUG] GbaRequest - GbaRequest: Constructor Called 222 userAgent Apache-HttpClient/UNAVAILABLE (java 1.4)
Thank you in advance for the assistance. I wasn't able to find a post regarding this error I received on my project.
I receive this error only sometimes, though I'm not sure why it comes up as it seems random when it occurs. I don't notice anything out of the ordinary in my data input.
My android application is attempting to make a connection to a remote server and push data into the PostgreSQL tables. Would anyone be able to refer me to the proper documentation for this error or explain its meaning. I appreciate the assistance.
Here is my code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser()
{
// Empty Constructor
}
public JSONObject getJSONFromUrl(String url)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e)
{
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params)
{
try
{
if (method == "POST")
{
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if (method == "GET")
{
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e)
{
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
That is not an error itself, Apache-HttpClient/UNAVAILABLE (java 1.4) is the default User Agent string for your Apache HttpClient.
This happens when you don't send the User Agent ("User-Agent:") via HTTP headers, then the phone GBA Service warn you about that.
If you want send the default system User Agent you can do
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
this should be like
Dalvik/1.6.0 (Linux; U; Android 4.2.2; Galaxy Nexus Build/JDQ39)
or if you want sent a custom User Agent you can do
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "My user agent");
or you can set the header via setHeader method
requestOrPost.setHeader("User-Agent", USER_AGENT);

How do you encode a url string in java to not put + signs in spaces?

I have a JSONParser class that would enable me to make HTTPRequests. So here is the class
package com.thesis.menubook;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
Log.d("URL",url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+ "n" );
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
Log.e("JSON Parser", "json string :" +json);
}
// return JSON String
return jObj;
}
}
I access it like this.
params.add(new BasicNameValuePair("category", "MAIN DISH"));
JSONObject json = jsonParser.makeHttpRequest("http://"+ipaddress+"/MenuBook/selectMenu.php", "GET", params);
I would like to keep the format of the parameter as such, MAIN DISH. but when I look into my LogCat it returns a url formed like this.
http://192.168.10.149:80/MenuBook/selectMenu.php?category=MAIN+DISH
which then causes my application to fail and force close since I have no category like MAIN+DISH
I would like my URL to be formed like this.
http://192.168.10.149:80/MenuBook/selectMenu.php?category='MAIN DISH'
which would then return the proper results. I searched around in the net and only found solutions to make white spaces + and %20 which would not return the proper result.
Any solutions you can suggest?
Your question embodies a contradiction in terms. URL-encoding (actually form-encoding) is already defined, and it is already defined to replace spaces with '+', not to quote the value elements concerned. The server-side software needs to understand that and behave accordingly. All the server-side software provided by Java, e.g. HttpServletRequest, already does that. If your code doesn't comply with the RFCs, fix it so it does.
I solved it by hardcoding it with 'MAIN+DISH'

Categories