This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
aim trying process http post for user login information by remote server
my code works good on 2.3.3 but on 4.1 and 4.2 the application is force closed
my AndroidManifest.xml file has
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17"
android:maxSdkVersion="17" />
and the code aim using for http post process is
public class postdata {
public static final String Logger = postdata.class.getName();
private static String slurp(InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
public static String post_string(String url, String urlParameters) throws IOException {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
} catch (MalformedURLException e) {
Log.e(Logger, "MalformedURLException While Creating URL Connection - " + e.getMessage());
throw e;
} catch (IOException e) {
Log.e(Logger, "IOException While Creating URL Connection - " + e.getMessage());
throw e;
}
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.length()));
OutputStream os = null;
try {
os = conn.getOutputStream();
} catch (IOException e) {
Log.e(Logger, "IOException While Creating URL OutputStream - " + e.getMessage());
throw e;
}
try {
os.write(urlParameters.toString().getBytes());
} catch (IOException e) {
Log.e(Logger, "IOException While writting URL OutputStream - " + e.getMessage());
throw e;
}
InputStream in = null;
try {
in = conn.getInputStream();
} catch (IOException e) {
Log.e(Logger, "IOException While Creating URL InputStream - " + e.getMessage());
throw e;
}
String output = null;
try {
output = slurp(in);
} catch (IOException e) {
Log.e(Logger, "IOException While Reading URL OutputStream - " + e.getMessage());
throw e;
} finally {
try {
os.close();
in.close();
} catch (IOException e) {
Log.e(Logger, "IOException While Closing URL Output and Input Stream - " + e.getMessage());
}
}
conn.disconnect();return output;
}
}
how to make my code work on all android versions without problem ?
You may be trying to perform Network operations on UI thread, please move your Network related operations to a background Thread, preferably an AsyncTask, see this example on how to do it correctly.
Related
I need to do soap request to web service. There are only 2 functions, so I decided to use simple HttpURLConnection so speed up development.
Here is the test code(don't be afraid of try/catch, it's just a test).
HttpURLConnection connection = null;
URL url = null;
try {
url = new URL("http://doc.ssau.ru/ssau_biblioteka_test/ws/DspaceIntegration.1cws");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
connection = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setRequestProperty("Authorization", "Basic d2Vic2VydmljZTp3ZWJzZXJ2aWNl");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
DataOutputStream wr = null;
try {
wr = new DataOutputStream(
connection.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
String myString = "RU/НТБ СГАУ/WALL/Х62/С 232-948516";
byte bytes[] = new byte[0];
try {
bytes = myString.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String value = "";
try {
value = new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
wr.writeBytes("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:imc=\"http://imc.parus-s.ru\">\n" +
" <soap:Header/>\n" +
" <soap:Body>\n" +
" <imc:GetRecordsInfo>\n" +
" <imc:Codes>RU/НТБ СГАУ/WALL/Х62/С 232-948516</imc:Codes>\n" +
" <imc:Separator>?</imc:Separator>\n" +
" <imc:Type>?</imc:Type>\n" +
" </imc:GetRecordsInfo>\n" +
" </soap:Body>\n" +
"</soap:Envelope>");
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
InputStream is = null;
try {
is = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
String line;
try {
while((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
So here is the question:
When I do wirteByes with cyrillyc characters, like "RU/НТБ СГАУ/WALL/Х62/С 232-948516", the web service returns 500. If I use only latin or leave empty, then everthing is ok.
What is the right way to encode cyrillyc?
UPDATE
Problem solved, used this construction:
wr.write(new String("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:imc=\"http://imc.parus-s.ru\">\n" +
" <soap:Header/>\n" +
" <soap:Body>\n" +
" <imc:GetRecordsInfo>\n" +
" <imc:Codes>RU/НТБ СГАУ/WALL/Х62/С 232-948516</imc:Codes>\n" +
" <imc:Separator>?</imc:Separator>\n" +
" <imc:Type>?</imc:Type>\n" +
" </imc:GetRecordsInfo>\n" +
" </soap:Body>\n" +
"</soap:Envelope>").getBytes(charset));
Not exactly sure that what might be going wrong, there are a couple of things you might try.
1)Try a different encoding. Following code might help.
Charset charset = Charset.forName("UTF-16");
byte[] encodedBytes = myString.getBytes(charset);
2)Another thing you can try is guessing the character set of your string.(Please Note : there is no way to guess the character set 100% right every time)
byte[] thisAppCanBreak = "this app can break"
.getBytes("ISO-8859-1");
CharsetDetector detector = new CharsetDetector();
detector.setText(thisAppCanBreak);
String tableTemplate = "%10s %10s %8s%n";
System.out.format(tableTemplate, "CONFIDENCE",
"CHARSET", "LANGUAGE");
for (CharsetMatch match : detector.detectAll()) {
System.out.format(tableTemplate, match
.getConfidence(), match.getName(), match
.getLanguage());
}
This link might be helpful too
I am uploading a file from one server to another server using a Java Program 'POST' method. But I am getting below exception.
java.io.IOException: Error writing to server
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:582)
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:594)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1216)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
at com.test.rest.HttpURLConnectionExample.TransferFile(HttpURLConnectionExample.java:107)
at com.test.rest.HttpURLConnectionExample.main(HttpURLConnectionExample.java:44)
I have other method who will authenticate with server. Which will be be called from below code. When I am getting response from server, I am getting above exception. To Transfer a file to server I have written below method. My sample code is below:
public static void TransferFile(){
String urlStr = "http://192.168.0.8:8600/audiofile?path=1/622080256/virtualhaircut.mp3";
File tempFile = new File("/home/MyPath/Workspace/Sample/virtualhaircut.mp3");
BufferedWriter br=null;
HttpURLConnection conn = null;
URL url;
try {
url = new URL(urlStr);
AuthenticationUser();
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", new MimetypesFileTypeMap().getContentType(tempFile.getName()));
} catch (MalformedURLException e1) {
System.out.println("Malformed");
e1.printStackTrace();
} catch (ProtocolException e) {
System.out.println("Protocol");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO");
e.printStackTrace();
}
System.out.println("line 69");
FileInputStream fis;
OutputStream fos;
try {
System.out.println("line 75");
System.out.println("line 77");
fis = new FileInputStream(tempFile);
fos = conn.getOutputStream();
byte[] buf = new byte[1024 * 2];
int len = 0;
System.out.println("line 80");
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
System.out.println("line 85");
}
System.out.println("line 87");
buf = null;
fos.flush();
fos.close();
fis.close();
}catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (conn.getResponseCode() == 200) {
System.out.println("here");
}
} catch (IOException e) {
e.printStackTrace();
}
}
It is possible that the error ocurred because the receiving server closed the connection, maybe because your file exceeded the size limit. Have you tested with small files?
I'm new to android, java and socket programming so of course I'm trying to merge all three!
I'm creating a desktop based java server which will simply send a short string to an android app(client).
I have the android app running fine and it sends strings to the server which are read with no problems.
I have the server running and it recieves the strings with no problems.
The app(client) however has a socket timeout whenever I try to read the strings returned from the server. I'm using the same code so I can't understand the problem.
Anyway here's the code:
//SERVER//
import java.io.*;
import java.net.*;
import java.util.*;
public class GpsServer {
ServerSocket serversocket = null;
Socket socket = null;
public GpsServer()
{
try
{
serversocket = new ServerSocket(8189);
}
catch (UnknownHostException unhe)
{
System.out.println("UnknownHostException: " + unhe.getMessage());
}
catch (InterruptedIOException intioe)
{
System.out.println("Timeout while attempting to establish socket connection.");
} catch (IOException ioe)
{
System.out.println("IOException: " + ioe.getMessage());
}
}
public void refreshServer() {
try
{
socket = serversocket.accept();
InputStreamReader inputstreamreader = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
PrintWriter printwriter = new PrintWriter(socket.getOutputStream(),true);
System.out.println("socket read successful");
printwriter.println("Send Bye to disconnect.");
String lineread = "";
boolean done = false;
while (((lineread = bufferedreader.readLine()) != null) && (!done)){
System.out.println("Received from Client: " + lineread);
printwriter.println("You sent: " + lineread);
if (lineread.compareToIgnoreCase("Bye") == 0) done = true;
}
System.out.println("Closing connection");
socket.close();
bufferedreader.close();
inputstreamreader.close();
printwriter.close();
}
catch (UnknownHostException unhe)
{
System.out.println("UnknownHostException: " + unhe.getMessage());
}
catch (InterruptedIOException intioe)
{
System.out
.println("Timeout while attempting to establish socket connection.");
}
catch (IOException ioe)
{
System.out.println("IOException: " + ioe.getMessage());
}
}
public void nullify() {
try
{
socket.close();
serversocket.close();
}
catch (IOException ioe)
{
System.out.println("IOException: " + ioe.getMessage());
}
}
}
and the client...
//CLIENT
import java.io.*;
import java.net.*;
import java.util.*;
public class GpsClient {
public String lastMessage;
Socket socket = null;
String serverurl;
int serverport;
public GpsClient() {
lastMessage = "";
serverport = 8189;
serverurl = "192.168.10.4";
try
{
socket = new Socket(serverurl, serverport);
socket.setSoTimeout(10000);
}
catch (UnknownHostException unhe)
{
System.out.println("UnknownHostException: " + unhe.getMessage());
}
catch (InterruptedIOException intioe)
{
System.out.println("Timeout while attempting to establish socket connection.");
}
catch (IOException ioe)
{
System.out.println("IOException: " + ioe.getMessage());
}
}
public void retrieveNew() {
try {
socket = new Socket(serverurl, serverport);
socket.setSoTimeout(10000);
lastMessage = "connected!";
InputStreamReader inputstreamreader = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
PrintWriter printwriter = new PrintWriter(socket.getOutputStream(),true);
printwriter.println("Request");
lastMessage = "Request sent";
// Get error when I uncomment this block, i.e. try to read the response from the server
// "Timeout while attempting to establish socket connection."
// String lineread = "";
// while ((lineread = bufferedreader.readLine()) != null) {
// System.out.println("Received from Server: " + lineread);
// lastMessage = "Received from Server: " + lineread;
// }
lastMessage = "closing connection!";
bufferedreader.close();
inputstreamreader.close();
printwriter.close();
socket.close();
}
catch (UnknownHostException unhe)
{
System.out.println("UnknownHostException: " + unhe.getMessage());
}
catch (InterruptedIOException intioe)
{
System.out.println("Timeout while attempting to establish socket connection.");
}
catch (IOException ioe)
{
System.out.println("IOException: " + ioe.getMessage());
}
finally
{
try
{
socket.close();
}
catch (IOException ioe)
{
System.out.println("IOException: " + ioe.getMessage());
}
}
}
public void nullify() {
try
{
PrintWriter printwriter = new PrintWriter(socket.getOutputStream(),true);
printwriter.println("Bye");
printwriter.close();
socket.close();
}
catch (IOException ioe)
{
System.out.println("IOException: " + ioe.getMessage());
}
}
}
Thanks in advance!
Josh
Apart from all the issues noted in my comment, you are creating two sockets in the client, and your server is only written to process one connection. So it writes to the first one and tries to read from it, meanwhile your client is writing to the second one and trying to read from that.
When you fix that you will then hit a deadlock, as both sides are trying to read from each other.
Also you shouldn't use PrintWriter or PrintStream over the network, as they swallow exceptions you need to know about. Use BufferedWriter.
Try putting something at the end of the server message, like ETX or something like <end> or wrap the message in <msg>...</msg>.
Then on Android in the while loop check if you received it instead of checking (lineread = bufferedreader.readLine()) != null.
I am new to java TCP socket. I tried to implement a server and a client. So the server should check input (do something) and send string to client. The client should send string to the server and look for an input string from the server (and do something). Both should loop checking and sending all the time if something new is available.
The client can send data to the server, the server receives it an can display/process this data.
But the data from the server isn't displayed by the client. Can someone tell me why the client isn't receiving the string from the server? Any better ideas to do endless loop? There will be only one client and one server.
while true:
server out------> send String-----> in client
in<----- sent String <------ out
this is the simplified server part:
public class MainActivity extends Activity {
Socket client;
ServerSocket server;
int serverport = 54321;
String inputData = null;
BufferedReader in;
PrintWriter out;
String outputData;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(setupConnection).start();
}
private Runnable setupConnection = new Thread() {
public void run() {
try {
server = new ServerSocket(serverport);
while (true) {
client = server.accept();
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
inputData = in.readLine();
InputStream inStream = new ByteArrayInputStream(inputData.getBytes());
in.close();
if (inputData != null) {
System.out.println(TAG + "-----Incoming Message---- " + inputData);
//this is working String is shown
} }
out.write("nothing to do?");
out.flush();
out.close();
}
} catch (SocketException e) {
Log.v(TAG, "SocketException: " + e);
e.printStackTrace();
} catch (IOException e) {
Log.v(TAG, "IOException: " + e);
e.printStackTrace();
}
}
the simplified client looks like this:
public class testClass {
public static void main(String[] args) throws IOException, InterruptedException {
Socket socket = null;
String host = "127.0.0.1";
int port = 54321;
PrintWriter out = null;
BufferedReader in = null;
while (true) {
try {
socket = new Socket(host, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println(TAG + "Error: " + e);
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.out.println(TAG + "Error: " + e);
System.err.println("Couldn't get I/O for " + "the connection to: localhost.");
System.exit(1);
}
out.println("Hello, is it me you're looking for...");
out.flush();
String input = in.readLine();
System.out.println("Input: " + input);
in.close();
out.close();
}
}
}
If readLine() returns null,the peer has closed the connection, and you must do likewise. And stop reading.
if you want implement this code in android , you faces many problems:
you can find the solution in this link:
Post JSON in android
in the following code may be fix this problem:
HttpPost post = new HttpPost("http://xxxxxx");
DefaultHttpClient httpClient = new DefaultHttpClient();
post.setEntity(new ByteArrayEntity(json.toString().getBytes()));
HttpResponse response = httpClient.execute(post);
return EntityUtils.toString(response.getEntity());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
System.out.println(">>>>>>>" + e.getMessage());
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println(">>>>>>>" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.println(">>>>>>>" + e.getMessage());
}
I can pull the user's statuses with no problem with cURL, but when I connect with Java, the xml comes out truncated and my parser wants to cry. I'm testing with small users so it's not choke data or anything.
public void getRuserHx(){
System.out.println("Getting user status history...");
String https_url = "https://twitter.com/statuses/user_timeline/" + idS.rootUser + ".xml?count=100&page=[1-32]";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(15*1000);
//dump all the content into an xml file
print_content(con);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished downloading user status history.");
}
private void print_content(HttpsURLConnection con){
if(con!=null){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
File userHx = new File("/" + idS.rootUser + "Hx.xml");
PrintWriter out = new PrintWriter(idS.hoopoeData + userHx);
String input;
while ((input = br.readLine()) != null){
out.println(input);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
This request doesn't need auth. Sorry about my ugly code. My professor says input doesn't matter so my I/O is a trainwreck.
You have to flush the output stream when you write the content out. Did you flush or close the output stream?