I am trying to send post to a server from android but it crashes while doing it.
I cannot see if any errors occured, I could not figure out how to monitor http requests in android studio.
Here is my code
try {
String rtoken = FirebaseInstanceId.getInstance().getToken();
Log.v("tokken", rtoken);
URL url = new URL("http://my website.com/yyy");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15001);
conn.setConnectTimeout(15001);
conn.setRequestMethod("POST");
conn.setRequestProperty("pid",jo.getString("parent_id"));
conn.setRequestProperty("sid",jo.getString("parent_id"));
conn.setRequestProperty("token",rtoken);
conn.setDoOutput(true);
OutputStream outputPost = new BufferedOutputStream(conn.getOutputStream());
writeStream(outputPost);
outputPost.flush();
outputPost.close();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (JSONException e1) {
e1.printStackTrace();
}
and the stack trace of crash
(JsonParser.java:105) is the line
OutputStream outputPost = new BufferedOutputStream(conn.getOutputStream());
I am really tired of this problem for hours. Any help will be appreciated, thanks,
You are not allowed to connect to the network on the main thread (ie. MainActivity or another View).
Instead, create an AsyncTask and connect to the web from there.
I recommend you to read this article about android Thread management. You are trying to do network on the main thread which freeze the UI, that's why you get the "NetworkOnMainThread" exception.
Try starting a new thread and do the networking there like:
(new Thread(){
#Override public void run(){
try {
String rtoken = FirebaseInstanceId.getInstance().getToken();
Log.v("tokken", rtoken);
URL url = new URL("http://my website.com/yyy");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15001);
conn.setConnectTimeout(15001);
conn.setRequestMethod("POST");
conn.setRequestProperty("pid",jo.getString("parent_id"));
conn.setRequestProperty("sid",jo.getString("parent_id"));
conn.setRequestProperty("token",rtoken);
conn.setDoOutput(true);
OutputStream outputPost = new BufferedOutputStream(conn.getOutputStream());
writeStream(outputPost);
outputPost.flush();
outputPost.close();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}).start();
Related
So my question is how can I create a DELETE Request to an URL in Android Studio Java. I already have an Async Task which GET json from URL. So my question now is how can I create a DELETE request
EDIT:
So right now I got this code:
int pos = arrlist.get(info.position).getId();
URL_DELETE = "http://testserver/test/tesst.php?id=" + pos + "&username=" + username + "&password=" + password;
URL url = null;
try {
url = new URL(URL_DELETE);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To understand the content of the given URL should be deleted. But if I run the code nothing happens.
You need to call connect() on the HttpURLConnection. Right now you're not actually making a connection to the server.
Based on your comments on the other answer, you're also trying to run this code on the main (UI) thread - you'll need to change your code to run on a background thread.
If you're using OkHttp:
Request request = new Request.Builder().delete().url(url).build();
Response rawResponse = null;
try {
rawResponse = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
System.err.println(e.getMessage());
}
String responseAsString = rawResponse.body().string();
I was trying several days to get HTTPS connection right to connect to Yobit public API. I don't know what happen to my code. I have tried so many different examples but nothing works out on Yobit. Those codes and examples I have tried, they either give 411, 503 error or MalFormException:no protocol. Can anyone help me? I have very limited experience with HTTPS or web programming on Java. If any one can provide me solutions and references, I will really appreciate that.
public void buildHttpsConnection()
{
try {
URL url = new URL("https://yobit.net/api/3/info");
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("user-Agent", "Mozilla/5.0 (compatible; JAVA AWT)");
con.setRequestProperty("Accept-Language","en-US,en;q=0.5");
con.setDoOutput(true);
con.setUseCaches(false);
System.out.println(con.getResponseCode());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Try to use "https://www.yobit.net/api/3/info" URL Instead of "https://yobit.net/api/3/info"
It will give you the same result. You can validate it from the browser Window.
Check below snippet.
try {
URL url = null;
try {
url = new URL("https://www.yobit.net/api/3/info");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
try {
con.setRequestMethod("GET");
} catch (ProtocolException e1) {
e1.printStackTrace();
}
con.setRequestProperty("user-Agent", "Mozilla/5.0 (compatible; JAVA AWT)");
con.setRequestProperty("Accept-Language","en-US,en;q=0.5");
con.setDoOutput(true);
con.setUseCaches(false);
con.connect();
try {
System.out.println(con.getResponseCode());
} catch (IOException e1) {
e1.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace();
}
I'm trying to download this html
I'm using this code:
Document doc = null;
try {
doc =Jsoup.connect(link).userAgent("Mozilla").get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i ("html", doc.toString());
UPDATED:
ASLO tried to use it:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(link);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
//
e1.printStackTrace();
} catch (IOException e1) {
//
e1.printStackTrace();
}
InputStream in = null;
try {
in = response.getEntity().getContent();
} catch (IllegalStateException e1) {
//
e1.printStackTrace();
} catch (IOException e1) {
//
e1.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
} catch (UnsupportedEncodingException e) {
//
e.printStackTrace();
}
StringBuilder str = new StringBuilder();
String line = null;
try {
while((line = reader.readLine()) != null)
{
str.append(line);
}
} catch (IOException e1) {
//
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
//
e1.printStackTrace();
}
String html = str.toString();
Log.e("html", html);
again responce like this one:
<html>
<body>
<script>document.cookie="BPC=f563534535121d5a1ba5bd1e153b";
document.location.href="http://...link.../all?attempt=1";</script>
</body>
</html>
I can't find any solution... Page can not be downloaded maybe because haven't cookie ... or what?
In the script tag, you have this statement :
document.location.href="....link..../all?attempt=1";
Normally it forces the browser to reload the page with the location. I think it's the page "....link...?attempt=1" that you want to download in fact.
It is not sure that it will work anyway if you don't use the cookie defined in the script but it deserves a try.
I have a following piece of code, basically copy-pasted from examples as I am new to Java and Android (not to programming):
URL vurl = new URL(voteurl); //vuteurl is a string containing a proper URL
HttpURLConnection hc;
hc=null;
hc = (HttpURLConnection)vurl.openConnection();
hc.setRequestMethod("GET");
hc.setDoOutput(true);
hc.setReadTimeout(10000);
hc.connect();
On the line "hc.connect();" the application crashes and Android informs me that it had been stopped.
Adding android.permission.INTERNET to the permisions used by the app did not help.
OK, turns out Android doesn't like network operations in the main thread.
Doing a request in a separate thread does the trick. Thanks guys for Your help!
URL vurl = null;
try {
vurl = new URL(voteurl);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //vuteurl is a string containing a proper URL
HttpURLConnection hc;
hc=null;
try {
hc = (HttpURLConnection)vurl.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
hc.setRequestMethod("GET");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hc.setDoOutput(true);
hc.setReadTimeout(10000);
try {
hc.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
How can I know the date a webpage last-modified using Android Java? or how I can request for
If-Modified-Since: Allows a 304 Not Modified to be returned if content is unchanged
using http headers?
I could do it this way:
URL url = null;
try {
url = new URL("http://www.example.com/example.pdf");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpURLConnection httpCon = null;
try {
httpCon = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long date = httpCon.getLastModified();