Http Url Connection error - java

I am getting the following error:
java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=CONNECT_URL
Following are my Global variables:
String CONNECT_URL = "http://api.openweathermap.org/data/2.5/weather?q=Mumbai";
int LAST_INDEX;
String NAME;
String TYPE;
String GREETING_YEAR;
String GREETING_GENERAL;
String RADIO_TYPE;
InputStream ins = null;
String result = null;
following is my parse function:
public void parse(){
DefaultHttpClient http = new DefaultHttpClient(new BasicHttpParams());
System.out.println("URL is: "+CONNECT_URL);
HttpPost httppost = new HttpPost("CONNECT_URL");
httppost.setHeader("Content-type", "application/json");
try{
HttpResponse resp = http.execute(httppost);
HttpEntity entity = resp.getEntity();
ins = entity.getContent();
BufferedReader bufread = new BufferedReader(new InputStreamReader(ins, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = bufread.readLine()) != null){
sb.append(line +"\n");
}
result = sb.toString();
System.out.println("Result: "+result);
}catch (Exception e){
System.out.println("Error: "+e);
}finally{
try{
if(ins != null){
ins.close();
}
}catch(Exception squish){
System.out.println("Squish: "+squish);
}
}
}
I tried to refator it with other similar questions on SO, but my URL seems to be okay and it returns the JSON once I check the same URL from a browser, any hints?

You´ve got
HttpPost httppost = new HttpPost("CONNECT_URL");
and looking to your code should be like
HttpPost httppost = new HttpPost(CONNECT_URL);

You are passing "CONNECT_URL" in HttpPost object which is wrong. Use
HttpPost httppost = new HttpPost(CONNECT_URL) //instead of HttpPost("CONNECT_URL")

HttpPost httppost = new HttpPost("CONNECT_URL");
should be
HttpPost httppost = new HttpPost(CONNECT_URL);
As a side note, Java convention dictates that variables are camel case (connectUrl) and constants are uppercase (CONNECT_URL).

I think the problem comes from this line:
HttpPost httppost = new HttpPost("CONNECT_URL");
You are passing the string "CONNECT_URL" instead of passing the variable CONNECT_URL :)

Related

How to send Json String using REST to java webservice in Parameter in android?

Fiends, i sending JSON String with three parameters to java web service method. but on java side method cant print in console. Please guide me what i have to change from below code?
String json = "";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "ghanshyam");
jsonObject.put("country", "India");
jsonObject.put("twitter", "ghahhd");
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
// 6. set httpPost Entity
System.out.println(json);
httpPost.setEntity(se);
httpGet.se
// 7. Set some headers to inform server about the type of the content
//httpPost.addHeader( "SOAPAction", "application/json" );
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//String s = doGet(url).toString();
Toast.makeText(getApplicationContext(), "Data Sent", Toast.LENGTH_SHORT).show();
Use the following code to post the json to Java web-service: and get the resopnse as a string.
JSONObject json = new JSONObject();
json.put("name", "ghanshyam");
json.put("country", "India");
json.put("twitter", "ghahhd");
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpresponse = client.execute(post);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
and Your convertStremToString() method will be as follows:
public static 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();
}

Android: JSON isn't working, Log.e returns a null

I am trying to get the USD average price 30d for bitcoins from here: http://api.bitcoincharts.com/v1/weighted_prices.json. The Json code I have does not work in the try/catch, and the error is a null (I have tried looking into other questions but all of them seem to return errors, whereas mine just returns a null):
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dogewidget);
TextView btctest = (TextView) findViewById(R.id.title);
//Create a new HTTP Client
DefaultHttpClient httpclient = new DefaultHttpClient();
//Setup the get request
HttpPost httppost = new HttpPost("http://api.bitcoincharts.com/v1/weighted_prices.json");
//Depending on web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
result = reader.readLine();
JSONObject jObject = new JSONObject(result);
JSONObject jsubObject = jObject.getJSONObject("USD");
String btcjson = jsubObject.getString("30d");
btctest.setText(btcjson);
} catch (Exception e) {
e.printStackTrace();
Log.e("error", "" + e.getMessage());
btctest.setText("Error " + e.getMessage());
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
}
}
Any help would be appreciated! Thanks.
Try this code.
private void get_value(String php) {
String responseString = null;
try{
HttpClient httpclient = new DefaultHttpClient();
String url ="your_url";
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Toast.makeText(getApplicationContext(),responseString,1000).show();
//The below code is for Separating values.It may varies according with your result
JSONArray ja = new JSONArray(responseString);
int x=Integer.parseInt(ja.getJSONObject(0).getString("your_string_name"));
} catch(Exception e) {
}
}

Use arabic text in android

How to get the arabic string in json format and how to display in android application
inputStreamReader. I get the json from server side And using the Windows-1256 encodingString to convert the arabic string but sometext not be shown correctly.
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
System.out.println(url + ":::url");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream,"windows-1256");
//new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader,8);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out
.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
I have been r & d around a day and finally success to parse my arabic json response getting from server using following code.So, may be helpful to you.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(Your_URL);
HttpResponse http_response= httpclient.execute(httppost);
HttpEntity entity = http_response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.i("Response", jsonText);
Now, use jsonText for your further requirement.
Thank You

How to send the string array of values in one key word using post method to the server

I am using this code but i am not able to send the string array:
httpclient = new DefaultHttpClient();
httppost = new HttpPost(Call_Server.UPLOAD_VIDEO);
MultipartEntity mpEntity = new MultipartEntity(
HttpMultipartMode.STRICT);
mpEntity.addPart("FILE_UPLOAD", new FileBody(videofile));
mpEntity.addPart("from_email", new StringBody(
Call_Server.useremail));
mpEntity.addPart("recipient_emails", new StringBody(
AddressArray));
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
You can do something like this.
// Prepare Category Array
for (String mBusinessID : mSelectedCategoryArray) {
reqEntity.addPart("CategoryCBG[]", new StringBody(mBusinessID));
}
Just add [] with you array tag and paas values in a loop in it.
Here CategoryCBG is the array tag. You can pass your values in this tag by using loop. it will post as an array on server.
Here is the complete code how I used it :
public String executeMultipartPost() throws Exception {
try {
ByteArrayOutputStream mByteOutputStream = new ByteArrayOutputStream();
mSelectedImage.compress(CompressFormat.JPEG, 75, mByteOutputStream);
byte[] mImageByteDate = mByteOutputStream.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(CONSTANTS.MAIN_URL_GLOBAL + CONSTANTS.BUSINESS_REGISTRATION_TAG);
ByteArrayBody mImageByteArray = new ByteArrayBody(mImageByteDate, Long.toString(System.currentTimeMillis()) + ".jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("logo_img", mImageByteArray);
reqEntity.addPart("name", new StringBody(txtBusinessName_business_registration.getText().toString()));
reqEntity.addPart("email", new StringBody(txtBusinessEmail_business_registration.getText().toString()));
reqEntity.addPart("contact_phone", new StringBody(txtBusinessPhone_business_registration.getText().toString()));
reqEntity.addPart("link_url", new StringBody(txtBusinessWebsite_business_registration.getText().toString()));
reqEntity.addPart("Address", new StringBody(txtStreetAddress_business_registration.getText().toString()));
reqEntity.addPart("City", new StringBody(txtCity_business_registration.getText().toString()));
reqEntity.addPart("State", new StringBody(txtState_business_registration.getText().toString()));
reqEntity.addPart("Zip", new StringBody(txtZip_business_registration.getText().toString()));
reqEntity.addPart("details", new StringBody(txtDetail_business_registration.getText().toString()));
reqEntity.addPart("products", new StringBody(txtService_business_registration.getText().toString()));
// Prepare Category Array
for (String mBusinessID : mSelectedCategoryArray) {
reqEntity.addPart("CategoryCBG[]", new StringBody(mBusinessID));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
mStringBuilder = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
mStringBuilder = mStringBuilder.append(sResponse);
}
return mStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
return "error";
}
}
Update
To cancel ongioing uploading you can use
httpClient.getConnectionManager().shutdown();

Android - Http Get Request

I'm trying to Get Request with code below but the stringbuilder is always null. The url is correct...
http://pastebin.com/mASvGmkq
EDIT
public static StringBuilder sendHttpGet(String url) {
HttpClient http = new DefaultHttpClient();
StringBuilder buffer = null;
try {
HttpGet get = new HttpGet(url);
HttpResponse resp = http.execute(get);
buffer = inputStreamToString(resp.getEntity().getContent());
}
catch(Exception e) {
debug("ERRO EM GET HTTP URL:\n" + url + "\n" + e);
return null;
}
debug("GET HTTP URL OK:\n" + buffer);
return buffer;
}
I usually do it like this:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
}
where output is a String-object.

Categories