URL url = new URL("http://maps.google.com/maps/api/geocode/json?address=1600%20Amphitheatre%20Parkway&sensor=false&client_id=my_client_id&key=my_key");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
InputStream in = httpURLConnection.getInputStream();
Its giving connection refused exception.
You forgot to actually connect:
URL url = new URL("yoururl");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
try {
// open the connection and get results as InputStream.
httpURLConnection.connect();
InputStream in = httpURLConnection.getInputStream();;
// do more things
} finally {
httpURLConnection.disconnect();
}
Also you can modify how you encode your URL to avoid errors:
private String REQUEST_URL = "http://maps.google.com/maps/api/geocode/json";
private String address = "1600 Amphitheatre Parkway";
URL url = new URL(REQUEST_URL + "?address=" + URLEncoder.encode(address, "UTF-8") + "&sensor=false&client_id=my_client_id&key=my_key"););
Related
I am calling Traccar API from my AsyncTask class. I need to pass JSON and Basic Authentication using POST method. I have this inside my doInBackground but it returns 400 Bad Request. I cannot pinpoint what's wrong. I'm pretty sure URL and credentials are all correct.
String credentials= "my_username:my_password";
String credBase64 = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT).replace("\n", "");
URL url = new URL("https://server.traccar.org/api/devices");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Authorization", credBase64);
if (this.postData!=null)
{
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(this.postData.toString());
writer.flush();
}
int statusCode = urlConnection.getResponseCode();
if(statusCode == 200)
{
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = inputStream.toString();
}
else
{
Log.e(TAG, "Error" + statusCode);
}
I am doing a Android app and trying to input a new data into the student database, the connection which is HttpURLConnection is ok. I got a problem which says: java.io.IOException: unexcepted end of stream on Connection {....(here is my host address}.
I think the main problem is the conn.getOutputStream(), and I have check that the stream is not closed.
public static void createUser(Student user){
//initialise
URL url = null;
HttpURLConnection conn = null;
final String methodPath="/friendfinder.student/";
try {
Gson gson =new Gson();
String stringUserJson=gson.toJson(user);
url = new URL(BASE_URI + methodPath);
//open the connection
conn = (HttpURLConnection) url.openConnection();
//set the timeout
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
//set the connection method to POST
conn.setRequestMethod("POST");
//set the output to true
conn.setDoOutput(true);
//set length of the data you want to send
conn.setFixedLengthStreamingMode(stringUserJson.getBytes().length);
//add HTTP headers
conn.setRequestProperty("Content-Type", "application/json");
//Send the POST out
PrintWriter out= new PrintWriter(conn.getOutputStream());
out.print(stringUserJson);
out.close();
Log.i("error",new Integer(conn.getResponseCode()).toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
}
Would someone take a look at my code and give me a suggestion please?
I would like to open an URL and submit the following parameters to it, but it only seems to work if I add the BufferedReader to my code. Why is that?
Send.php is a script what will add an username with a time to my database.
This following code does not work (it does not submit any data to my database):
final String base = "http://awebsite.com//send.php?";
final String params = String.format("username=%s&time=%s", username, time);
final URL url = new URL(base + params);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Agent");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
But this code does work:
final String base = "http://awebsite.com//send.php?";
final String params = String.format("username=%s&time=%s", username, time);
final URL url = new URL(base + params);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Agent");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
connection.disconnect();
As far as I know. When you called the connect() function, it will only create the connection.
You need to at least call the getInputStream() or getResponseCode() for the connection to be committed so that the server that the url is pointing to able to process the request.
Getting unauthorize execption while connecting to share point rest web service:
URL myURL = new URL("http://test:2014/PWA/_api/ProjectData/Projects");
URLConnection uc = myURL.openConnection();
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String userCredentials = "admin:pasword";
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary("password".getBytes());
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
Getting following errors while reading from url
java.io.IOException: Server returned HTTP response code: 401 for URL: http://test:2014/PWA/_api/ProjectData/Projects
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.jw.sharepoint.examples.XMLParser.getDocumentFromUrl(XMLParser.java:127)
at com.jw.sharepoint.examples.XMLParser.main(XMLParser.java:27)
java.lang.NullPointerException
at com.jw.sharepoint.examples.XMLParser.main(XMLParser.java:29)
Add request property and request method solved the problem.
InputStream getAuthenticatedResponse(final String urlStr, final String domain,final String userName, final String password) throws IOException {
Authenticator.setDefault(new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
domain + "\\" + userName, password.toCharArray());
}
});
URL urlRequest = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "*/*");
return conn.getInputStream();
}
url = new URL(UPLOAD_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("content-type", "application/json");
urlConnection.setFixedLengthStreamingMode(responseJSONArray.toString(2).getBytes("UTF8").length);
urlConnection.setDoInput(false);
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(this.CONNECT_TIMEOUT);
urlConnection.connect();
OutputStream output = urlConnection.getOutputStream();
output.write(responseJSONArray.toString(2).getBytes("UTF8"));
output.close();
I've also already earlier set the Authenticator with:
Authenticator.setDefault(new Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(loginNameString, passwordString.toCharArray());
}
});
I supply correct login details, but the server responds with a 401 code. (A similar GET-request works though.) On top of which, the method getPasswordAuthentication() is not being called in the process of connecting and writing to the stream. (I know this because I put in Log.v("app", "password here").)
Why is that?
I'm not able to answer to why using Authenticator does not work, but I usually use this approach:
String webPage = "http://192.168.1.1";
String name = "admin";
String password = "admin";
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
Try it. Using basic auth should be enough.